package me.fangx.zhihu.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;
import me.fangx.common.ui.activity.BaseAppCompatActivity;
import me.fangx.common.util.eventbus.EventCenter;
import me.fangx.common.util.netstatus.NetUtils;
import me.fangx.zhihu.R;
import me.fangx.zhihu.adapter.CookPagerAdapter;
import me.fangx.zhihu.adapter.NavDrawerListAdapter;
import me.fangx.zhihu.modle.bean.NavDrawerItem;
import me.fangx.zhihu.utils.BaseUtil;
import me.fangx.zhihu.utils.NightModeHelper;

/**
 * Created by fangxiao on 15/12/01.
 */
public class HomeActivity extends BaseAppCompatActivity {

    private ListView mDrawerMenu;
    private String[] mNavMenuTitles;
    private TypedArray mNavMenuIconsTypeArray;
    private TypedArray mNavMenuIconTintTypeArray;
    private ArrayList<NavDrawerItem> mNavDrawerItems;
    private NavDrawerListAdapter mAdapter;
    private Toolbar actionBarToolbar;
    private DrawerLayout drawerLayout;
    private int position;

    @Bind(R.id.home_layout)
    LinearLayout home_layout;
    @Bind(R.id.nv_drawer_layout)
    LinearLayout nv_drawer_layout;
    @Bind(R.id.tv_change_theme)
    TextView tv_change_theme;
    @Bind(R.id.explore_content)
    LinearLayout explore_content;
    @Bind(R.id.explore_pager_tabs)
    TabLayout explore_pager_tabs;
    @Bind(R.id.explore_pager)
    ViewPager explore_pager;

    //日夜模式切换
    private NightModeHelper nightModeHelper;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_home;
    }

    @Override
    protected void initViewsAndEvents() {
        init();
        setupToolbar();
        setUpDrawer();
    }

    @OnClick(R.id.tv_change_theme)
    public void viewClick() {
        changeTheme(home_layout);
    }

    private void init() {
        nightModeHelper = new NightModeHelper(this);
        explore_pager.setOffscreenPageLimit(CookPagerAdapter.PAGE_COUNT);
        final CookPagerAdapter adapter = new CookPagerAdapter(getSupportFragmentManager(), this);
        explore_pager.setAdapter(adapter);
        explore_pager_tabs.setupWithViewPager(explore_pager);
        explore_pager_tabs.setTabMode(TabLayout.MODE_FIXED);
        explore_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                CookCategoryFragment exploreChildFragment =  adapter.getFB(position);
//                if(exploreChildFragment != null && exploreChildFragment.getExplore_recycleview() != null){
//                    explore_fab.attachToRecyclerView(exploreChildFragment.getExplore_recycleview());
//                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void setupToolbar() {
        actionBarToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(actionBarToolbar);
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }


    private void setUpDrawer() {

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawerLayout == null) {
            // current activity does not have a drawer.
            return;
        }
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(HomeActivity.this, drawerLayout, actionBarToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        drawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerMenu = (ListView) findViewById(R.id.left_menu);
        mNavMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        // nav drawer icons from resources
        mNavMenuIconsTypeArray = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);
        mNavMenuIconTintTypeArray = getResources()
                .obtainTypedArray(R.array.nav_drawer_tint);
        mNavDrawerItems = new ArrayList<NavDrawerItem>();
        for (int i = 0; i < mNavMenuTitles.length; i++) {
            mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[i], mNavMenuIconsTypeArray
                    .getResourceId(i, -1), mNavMenuIconTintTypeArray.getResourceId(i, -1)));
        }
        mNavMenuIconsTypeArray.recycle();
        // setting the nav drawer list adapter
        mAdapter = new NavDrawerListAdapter(this,
                mNavDrawerItems);
        mDrawerMenu.setAdapter(mAdapter);
        mDrawerMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!BaseUtil.isEmpty(mNavDrawerItems, i)) {
                    NavDrawerItem navDrawerItem = mNavDrawerItems.get(i);
                    if (navDrawerItem != null) {
                        selectItem(i, navDrawerItem.getTitle());
                    }
                }
            }
        });
    }


    protected void openDrawer() {
        if (drawerLayout == null)
            return;
        drawerLayout.openDrawer(GravityCompat.START);
    }

    protected void closeDrawer() {
        if (drawerLayout == null)
            return;
        drawerLayout.closeDrawer(GravityCompat.START);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sample_actions, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    closeDrawer();
                } else {
                    openDrawer();
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {

    }

    @Override
    protected View getLoadingTargetView() {
        return explore_content;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return TransitionMode.FADE;
    }

    /**
     * 左侧drawer选择事件
     *
     * @param position
     * @param title
     */
    public void selectItem(int position, String title) {
        this.position = position;
        switch (position) {
            case 0:
                //收藏
                startActivity(new Intent(this, CollectActivity.class));
                break;
            default:
                break;
        }
        closeDrawer();
    }


    /**
     * 主题切换
     *
     * @param view
     */
    private void changeTheme(final View view) {
        nightModeHelper.toggle();
    }

    @Override
    public void onBackPressed() {

        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            closeDrawer();
            return;
        } else {
            showCloseDialog();
        }

    }

    private void showCloseDialog() {
        Dialog dialog = new android.app.AlertDialog.Builder(this, 5)
                .setTitle(getResources().getString(R.string.tips))
                .setMessage(R.string.sure_to_leave)
                .setPositiveButton(R.string.btn_OK, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        System.exit(0);
                    }
                }).setNeutralButton(R.string.btn_Cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create();
        dialog.setCancelable(false);
        dialog.show();
    }
}
